package com.demo.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例注册表模式
 * 
 * @author libo
 * @version 1.0
 * @date 2018/5/9 16:02
 */
public class SingtonRegistry {

    private static final Map<String, Object> singtonObjects = new ConcurrentHashMap<>();

    private SingtonRegistry() {
    }

    private static class SingtonHolder {
        public static final SingtonRegistry singtonRegistry = new SingtonRegistry();
    }

    public static SingtonRegistry getInstance() {
        return SingtonHolder.singtonRegistry;
    }

    public Object getBean(String className) {
        Object singtonObject = singtonObjects.get(className);
        if (singtonObject == null) {
            synchronized (singtonObjects) {
                singtonObject = singtonObjects.get(className);
                if (singtonObject == null) {
                    try {
                        singtonObject = Class.forName(className).newInstance();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (singtonObject != null) {
                        singtonObjects.put(className, singtonObject);
                    }
                }
            }
        }
        return singtonObject;
    }
}
